package com.fxcalibre.fxml.control;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.CheckBox;
import javafx.scene.control.SplitPane;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;

import com.fxcalibre.db.beans.MediaItem;
import com.fxcalibre.fxml.control.events.DataChangedEvent;
import com.fxcalibre.fxml.view.FXMLViewLoader;
import com.fxcalibre.hibernate.GenericCriteria;
import com.fxcalibre.hibernate.HibernateUtils;
import com.fxcalibre.hibernate.dao.MediaItemsDAO;
import com.fxcalibre.utils.FileUtils;

public class MediaListPanel extends BorderPane
{
	@FXML
	SplitPane splitPane;
	@FXML
	StackPane filtersPanel;
	@FXML
	StackPane detailPanel;
	@FXML
	StackPane tablePanel;
	@FXML
	CheckBox showFilters;
	@FXML
	CheckBox showDetail;

	@FXML
	TableView<MediaItem> mediaTable;
	@FXML
	private TableColumn<MediaItem, String> nameColumn;
	@FXML
	private TableColumn<MediaItem, String> yearColumn;
	@FXML
	private TableColumn<MediaItem, String> typeColumn;
	@FXML
	private TableColumn<MediaItem, String> seasonColumn;
	@FXML
	private TableColumn<MediaItem, String> episodeColumn;

	@FXML
	TreeFilter treeFilter;
	@FXML
	MediaDetail mediaDetail;

	Stage primaryStage;

	ObservableList<MediaItem> tableData = FXCollections.observableArrayList(MediaItemsDAO.getMediaItems());
	ObservableList<GenericCriteria> filters = FXCollections.observableArrayList();

	public MediaListPanel()
	{
		FXMLViewLoader.load(this, "MediaListPanel.fxml");

		mediaTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
		mediaTable.setItems(tableData);

		// titleColumn.prefWidthProperty().bind(mediaTable.widthProperty().divide(100
		// / 60));
		// yearColumn.prefWidthProperty().bind(mediaTable.widthProperty().divide(100
		// / 20));
		// typeColumn.prefWidthProperty().bind(mediaTable.widthProperty().divide(100
		// / 20));

		// Listen for selection changes
		mediaTable.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<MediaItem>()
		{
			@Override
			public void changed(ObservableValue<? extends MediaItem> observable, MediaItem oldValue, MediaItem newValue)
			{
				mediaDetail.setMediaItem(newValue);
			}
		});

		mediaTable.addEventHandler(MouseEvent.MOUSE_CLICKED, new DoubleClickHandler());
		// loadFilterTree();
		addEventHandler(DataChangedEvent.DATA_CHANGED, new EventHandler<DataChangedEvent>()
		{
			@Override
			public void handle(DataChangedEvent event)
			{
				if (event.getEventType().equals(DataChangedEvent.DATA_CHANGED))
				{
					System.out.println("DATA CHANGEDMLP!!!!!");
					reload();
				}
			}
		});

		treeFilter.setFilters(filters);
	}

	@FXML
	private void addFromFolder(ActionEvent event)
	{
		System.out.println("addFromFolder!!");
		DirectoryChooser directoryChooser = new DirectoryChooser();
		File dir = directoryChooser.showDialog(null);
		if (dir != null && dir.exists())
		{
			List<File> files = FileUtils.getFiles(dir);
			for (Iterator<File> iterator = files.iterator(); iterator.hasNext();)
			{
				try
				{
					File file = iterator.next();
					MediaItem mediaItem = new MediaItem();
					mediaItem.setFile(file.getAbsolutePath());
					mediaItem.setName(file.getName());
					HibernateUtils.grabar(mediaItem);
				} catch (Exception e)
				{
					e.printStackTrace();
				}
			}

			fireEvent(new DataChangedEvent());
		}
	}

	@FXML
	private void addMediaItem(ActionEvent event)
	{
		System.out.println("addMediaItem!!");
		MediaDetail mediaDetailForPopup = new MediaDetail();
		mediaDetailForPopup.setMediaItem(new MediaItem());
		mediaDetailForPopup.showInStage();
		reload();
	}

	@SuppressWarnings("unchecked")
	public void reload()
	{
		if (filters.size() > 0)
		{
			System.out.println("Add with filters");
			tableData.clear();
			tableData.addAll((List<MediaItem>) HibernateUtils.buscar(filters.get(0)));
		} else
		{
			tableData.clear();
			tableData.addAll(MediaItemsDAO.getMediaItems());
		}
	}

	@FXML
	private void repaint(ActionEvent event)
	{
		System.out.println("showFilters: " + showFilters.isSelected());
		System.out.println("showDetail: " + showDetail.isSelected());

		splitPane.getItems().clear();
		if (showFilters.isSelected())
		{
			splitPane.getItems().add(filtersPanel);
		}

		splitPane.getItems().add(tablePanel);

		if (showDetail.isSelected())
		{
			splitPane.getItems().add(detailPanel);
		}

		if (splitPane.getItems().size() == 3)
		{
			splitPane.setDividerPositions(0.1f, 0.7f);
		}

		if (splitPane.getItems().size() == 2 && showFilters.isSelected())
		{
			splitPane.setDividerPositions(0.2f);
		}

		if (splitPane.getItems().size() == 2 && showDetail.isSelected())
		{
			splitPane.setDividerPositions(0.7f);
		}
	}

	class DoubleClickHandler implements EventHandler<MouseEvent>
	{

		@SuppressWarnings("unchecked")
		@Override
		public void handle(MouseEvent event)
		{
			if (event.getClickCount() > 1)
			{
				System.out.println("double clicked!:" + event.getTarget());
				MediaItem mediaItem = ((TableView<MediaItem>) event.getSource()).getSelectionModel().getSelectedItem();
				MediaDetail mediaDetailForPopup = new MediaDetail();
				mediaDetailForPopup.setPrimaryStage(primaryStage);
				mediaDetailForPopup.setMediaItem(mediaItem);
				mediaDetailForPopup.showInStage();

				reload();
			}
		}
	}

	public Stage getPrimaryStage()
	{
		return primaryStage;
	}

	public void setPrimaryStage(Stage primaryStage)
	{
		this.primaryStage = primaryStage;
	}

}
